import time
from datetime import datetime
from datetime import timedelta

import backtrader as bt

from ccxtbt import CCXTFeed


def main():
    class TestStrategy(bt.Strategy):
        def __init__(self):
            self.next_runs = 0

        def next(self, dt=None):
            dt_now = datetime.now()
            dt = dt or self.datas[0].datetime.datetime(0) + timedelta(hours=8)

            print('time: %s dtime: %s close: %s volume: %s' % (dt_now.strftime("%Y-%m-%d %H:%M:%S"), dt.strftime("%Y-%m-%d %H:%M:%S"), self.datas[0].close[0], self.data.volume[0]))
            self.next_runs += 1

    cerebro = bt.Cerebro()

    cerebro.addstrategy(TestStrategy)

    # Add the feed
    cerebro.adddata(CCXTFeed(exchange='binance',
                             dataname='BNB/USDT',
                             timeframe=bt.TimeFrame.Minutes,
                             fromdate=datetime(2021, 5, 20, 2, 40),
                             # todate=datetime(2021, 5, 20, 2, 29),
                             compression=5,
                             ohlcv_limit=999,
                             currency='BNB',
                             retries=5,
                             # 'apiKey' and 'secret' are skipped
                             config={'enableRateLimit': True, 'nonce': lambda: str(int(time.time() * 1000))}))

    # Run the strategy
    cerebro.run()


if __name__ == '__main__':
    main()
